package com.reguang.handler;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import com.reguang.enums.ResultCode;
import com.reguang.exception.BaseException;
import com.reguang.result.ErrorResult;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * <p>Title: GlobalExceptionHandler</p>
 * <p>Description: 统一异常处理</p>
 * @author weibiao
 * @date 2019年12月24日
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	/**
	 * 
	 * <p>Title: handler</p>
	 * <p>Description: 定义要捕获的异常 可以多个 @ExceptionHandler({})</p>
	 * @param request
	 * @param exception
	 * @param response
	 * @return
	 */
	@ExceptionHandler({ Exception.class, //
			BaseException.class, //
			MethodArgumentNotValidException.class, //
			MissingServletRequestParameterException.class })
	public ErrorResult handler(HttpServletRequest request, final Exception exception, HttpServletResponse response) {
		if (exception instanceof BaseException) {
			BaseException e = (BaseException) exception;
			log.error("\n【当前错误编码】 errorCode : {}\n【当前错误信息】errorMsg : {}", e.getResultCode().code(),
					e.fillInStackTrace());// 记录日志
			response.setStatus(e.getHttpStatus());
			return ErrorResult.failure(e.getResultCode());
		}
		if (exception instanceof MethodArgumentNotValidException) {
			MethodArgumentNotValidException validException = (MethodArgumentNotValidException) exception;
			List<FieldError> fieldErrors = validException.getBindingResult().getFieldErrors();
			JsonArray jsonArray = new JsonArray();
			for (FieldError fieldError : fieldErrors) {
				JSONObject jsonObject = new JSONObject();
				jsonObject.put(fieldError.getField(), fieldError.getDefaultMessage());
				jsonArray.add(jsonObject.toString());
			}
			log.error("【错误信息】：{}", StringEscapeUtils.unescapeEcmaScript(jsonArray.toString()));
			response.setStatus(HttpStatus.BAD_REQUEST.value());
			return ErrorResult.failure(ResultCode.PARAM_IS_INVALID,
					StringEscapeUtils.unescapeEcmaScript(jsonArray.toString()));
		}
		if (exception instanceof MissingServletRequestParameterException) {
			MissingServletRequestParameterException requestParameterException = (MissingServletRequestParameterException) exception;
			log.error("【错误信息】：{}", "缺少参数：" + requestParameterException.getParameterName());
			response.setStatus(HttpStatus.BAD_REQUEST.value());
			return ErrorResult.failure(ResultCode.PARAM_IS_INVALID,
					"缺少参数：" + requestParameterException.getParameterName());
		}
		response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());// 默认500，服务器内部错误
		log.error("\n【当前错误编码】 errorCode : {}\n【当前错误信息】errorMsg : {}", ResultCode.SERVER_INTERNAL_ERROR.code(),
				exception.fillInStackTrace());// 记录日志
		return ErrorResult.failure(ResultCode.SERVER_INTERNAL_ERROR);
	}
}
